{% extends "menu.html" %}
{% block title %}个人主页{% endblock %}
{% block content %}
    <div class="flex h-full">
        <!-- 左侧面板 -->
        <div class="w-1/3 bg-gray-50 p-8 shadow-md">
            <h1 class="text-4xl font-bold text-gray-800 mb-8">个人主页</h1>

            <div id="profile" class="mb-8">
                <!-- 用户信息将显示在这里 -->
                <p class="text-lg">加载用户信息中...</p>
            </div>

            <h2 class="text-2xl font-semibold text-gray-700 mb-4">上传术语库</h2>
            <form id="uploadForm" enctype="multipart/form-data" class="space-y-4">
                <input type="file" name="file" accept=".csv,.xlsx" required
                       class="w-full p-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500">
                <input type="text" name="table_name" placeholder="术语表名称" required
                       class="w-full p-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500">
                <input type="text" name="category" placeholder="分类" required
                       class="w-full p-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500">
                <button type="submit"
                        class="w-full bg-green-500 text-white p-3 rounded hover:bg-green-700 transition duration-200">
                    上传
                </button>
            </form>

            <h2 class="text-2xl font-semibold text-gray-700 mt-8 mb-4">我的术语集</h2>
            <div id="termCollections" class="space-y-4">
                <!-- 术语集列表将在这里显示 -->
            </div>
        </div>
    </div>

    <script>
        console.log('Profile script running');
        const token = localStorage.getItem('jwtToken');
        console.log('Token retrieved:', token);

        if (!token) {
            window.location.href = '/login';
        } else {
            // 验证 JWT token
            fetch('/verify_token', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Token 验证失败');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.valid) {
                        fetchUserProfile();
                        fetchTermCollections();
                    } else {
                        throw new Error('Token 无效');
                    }
                })
                .catch(error => {
                    console.error('Token 验证失败:', error);
                    localStorage.removeItem('jwtToken');
                    window.location.href = '/login';
                });
        }

        function fetchUserProfile() {
            fetch('/access_profile', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应错误');
                    }
                    return response.json();
                })
                .then(data => {
                    const profileDiv = document.getElementById('profile');
                    profileDiv.innerHTML = `
                    <p><strong>昵称：</strong> ${data.nickname}</p>
                    <p><strong>邮箱：</strong> ${data.email}</p>
                `;
                })
                .catch(error => {
                    console.error('请求失败:', error);
                });
        }

        function fetchTermCollections() {
            fetch('/get_user_term_collections', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
                .then(response => response.json())
                .then(data => {
                    const termCollectionsDiv = document.getElementById('termCollections');
                    termCollectionsDiv.innerHTML = '';
                    data.forEach(collection => {
                        const collectionDiv = document.createElement('div');
                        collectionDiv.className = 'term-collection';
                        collectionDiv.innerHTML = `
                        <span>${collection.table_name}</span>
                        <button class="delete-btn" onclick="deleteTermCollection(${collection.id})">删除</button>
                    `;
                        termCollectionsDiv.appendChild(collectionDiv);
                    });
                })
                .catch(error => {
                    console.error('获取术语集失败:', error);
                });
        }

        function deleteTermCollection(collectionId) {
            if (confirm('确定要删除这个术语集吗？')) {
                fetch(`/delete_term_collection/${collectionId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                })
                    .then(response => response.json())
                    .then(data => {
                        alert(data.message);
                        fetchTermCollections(); // 重新加载术语集列表
                    })
                    .catch(error => {
                        console.error('删除术语集失败:', error);
                        alert('删除失败，请重试');
                    });
            }
        }

        document.getElementById('uploadForm').addEventListener('submit', function (e) {
            e.preventDefault();
            const formData = new FormData(this);

            fetch('/upload_term_collection', {
                method: 'POST',
                body: formData,
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
                .then(response => response.json())
                .then(data => {
                    alert(data.message);
                    fetchTermCollections(); // 刷新术语集列表
                })
                .catch(error => {
                    console.error('上传失败:', error);
                    alert('上传失败，请重试');
                });
        });
    </script>

{% endblock %}